import { Footer } from '@/components';
import { login } from '@/services/ant-design-pro/api';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { LoginForm, ProFormText } from '@ant-design/pro-components';
import { history, useModel, Helmet } from '@umijs/max';
import { message, Tabs } from 'antd';
import Settings from '../../../config/defaultSettings';
import React, { useState } from 'react';
import { flushSync } from 'react-dom';
import { setToken } from '@/utils';
import ForgotPasswordForm from '@/pages/Login/ForgotPasswordForm';
import useStyles from './useStyles.less';

const Login: React.FC = () => {
  const [type, setType] = useState<string>('account');
  const { initialState, setInitialState } = useModel('@@initialState');
  const [forgotPassword, setForgotPassword] = useState(false);
  const fetchUserInfo = async (data) => {
    if (data) {
      flushSync(() => {
        // 更新全局保存的用户信息
        setInitialState((s) => ({
          ...s,
          currentUser: {
            ...data,
          },
        }));
      });
    }
  };
  const handleSubmit = async (values) => {
    // 登录
    let { data } = await login({
      userName: values.username,
      password: values.password,
    });
    if (data.token) {
      setToken(data.token);
      const defaultLoginSuccessMessage = '登录成功！';
      message.success(defaultLoginSuccessMessage);
      await fetchUserInfo(data);
      // const urlParams = new URL(window.location.href).searchParams;
      // 跳转至首页
      history.push('/');
    }
  };

  const updatePasswordStatus = (flag) => {
    setForgotPassword(flag);
  };

  return (
    <div className={useStyles.container}>
      <Helmet>
        <title>
          {'登录'}- {Settings.title}
        </title>
      </Helmet>

      {/*忘记密码，重置密码表单*/}
      {forgotPassword && <ForgotPasswordForm updatePasswordStatus={updatePasswordStatus} />}

      {!forgotPassword && (
        <div style={{ marginTop: '5%' }}>
          <LoginForm
            contentStyle={{
              minWidth: 280,
              maxWidth: '75vw',
            }}
            logo={<img alt="logo" src="/logo.svg" />}
            title="用户管理中心"
            initialValues={{
              autoLogin: false,
              username: 'admin001',
              password: 'Abc123',
            }}
            onFinish={async (values) => {
              await handleSubmit(values as API.LoginParams);
            }}
          >
            <Tabs
              activeKey={type}
              onChange={setType}
              centered
              items={[
                {
                  key: 'account',
                  label: '账户密码登录',
                },
              ]}
            />

            <>
              <ProFormText
                name="username"
                fieldProps={{
                  size: 'large',
                  prefix: <UserOutlined />,
                }}
                placeholder={'请输入用户名'}
                rules={[
                  {
                    required: true,
                    message: '用户名是必填项！',
                  },
                ]}
              />
              <ProFormText.Password
                name="password"
                fieldProps={{
                  size: 'large',
                  prefix: <LockOutlined />,
                }}
                placeholder={'请输入密码'}
                rules={[
                  {
                    required: true,
                    message: '密码是必填项！',
                  },
                ]}
              />
            </>

            <div
              style={{
                marginBottom: 24,
              }}
            >
              <a
                style={{
                  float: 'right',
                  marginBottom: 20,
                }}
                onClick={() => updatePasswordStatus(true)}
              >
                忘记密码 ?
              </a>
            </div>
          </LoginForm>
        </div>
      )}
      <Footer />
    </div>
  );
};
export default Login;
